var appKey = 'pwe86ga5ema46';
RongIMLib.RongIMClient.init(appKey);
var db = openDatabase('messageChat', '1.0', 'messageChatOfHistory DB', 4 * 1024 * 1024);
db.transaction(function(tx) {
	tx.executeSql('CREATE TABLE IF NOT EXISTS CurentOtherMessage( Id, Phone,GuideId, MessageType, Message)');
});

/*function hasUread(token) {
	RongIMClient.getInstance().hasRemoteUnreadMessages(token, {
		onSuccess: function(hasMessage) {
			if (hasMessage) { // 有未读的消息				
				document.getElementById('info').style.display = 'block';
			}
		},
		onError: function(err) {
			// 错误处理...
		}
	});
}*/

function hasUreadmsg() {
	db.transaction(function(tx) {
		tx.executeSql('SELECT * FROM CurentOtherMessage ', [], function(tx, results) {
			var len = results.rows.length;
			if (len > 0) {
				document.getElementById('info').style.display = 'block';
			}
		}, null);
	});
}
//denglu
function loginRong() {
	var token = readData(localStorage.noticeToken);
	var phone = readData(localStorage.phone);
	hasUreadmsg();

	function dbInsertOther(msg) {
		if (msg.conversationType == 1) {
			db.transaction(function(tx) {
				tx.executeSql('INSERT INTO CurentOtherMessage (Id, Phone, GuideId, MessageType, Message) VALUES (?,?,?,?,?)', [msg.senderUserId, phone, msg.content.extra, msg.conversationType, JSON.stringify(msg)]);
			});
		} else {
			db.transaction(function(tx) {
				tx.executeSql('INSERT INTO CurentOtherMessage (Id, Phone, GuideId, MessageType, Message) VALUES (?,?,?,?,?)', [msg.targetId, phone, msg.content.extra, msg.conversationType, JSON.stringify(msg)]);
			});
		}

	}
	// 设置连接监听状态 （ status 标识当前连接状态 ）连接状态监听器
	RongIMClient.setConnectionStatusListener({
		onChanged: function(status) {
			switch (status) {
				case RongIMLib.ConnectionStatus.CONNECTED:
					console.log('链接成功');
					break;
				case RongIMLib.ConnectionStatus.CONNECTING:
					console.log('正在链接');
					break;
				case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
					break;
			}
			console.log(status);
		}
	});
	// 消息监听器
	RongIMClient.setOnReceiveMessageListener({
		// 接收到的消息
		onReceived: function(message) {
			if (!message.content.extra) {
				message.content.extra = message.senderUserId;
			}
			dbInsertOther(message);
			hasUreadmsg();
		}
	});
	//连接融云服务器8fa11a42-18a0-431e
	RongIMClient.connect(token, {
		onSuccess: function(userId) {
			console.log("Login successfully." + userId);
		},
		onTokenIncorrect: function() {
			console.log('token无效');
		},
		onError: function(errorCode) {
			var info = '';
			switch (errorCode) {
				case RongIMLib.ErrorCode.TIMEOUT:
					info = '超时';
					break;
				case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
					info = 'appkey不正确';
					break;
			}
			console.log(errorCode);
		}
	});
}